package rahmath.sharif.docrypt;

import rahmath.sharif.docrypt.constant.DocryptConstants;
import rahmath.sharif.docrypt.entity.Vault;
import rahmath.sharif.docrypt.util.AESCryptor;
import rahmath.sharif.docrypt.util.DocryptUtil;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class ManageDataActivity extends Activity implements DocryptConstants {

	@TargetApi(11)
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_manage_data);
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		Bundle bundle = getIntent().getExtras();
		Vault vault = DocryptUtil.getVaultFromSD(bundle
				.getString(VAULT_FILE_NAME));
		EditText editTextTextData = ((EditText) findViewById(R.id.editTextTextData));
		editTextTextData.setText(DocryptUtil.getCleanTextFromFile(
				bundle.getString(VAULT_PASSWORD),
				vault.getDatas().get(bundle.getString(DATA_KEY))
						.getTextFileName()));
	}

	public void save(View view) {
		final EditText editTextTextData = ((EditText) findViewById(R.id.editTextTextData));
		final Bundle bundle = getIntent().getExtras();
		final Vault vault = DocryptUtil.getVaultFromSD(bundle
				.getString(VAULT_FILE_NAME));

		DialogInterface.OnClickListener confirmDialog = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case DialogInterface.BUTTON_POSITIVE:
					String cipherText = AESCryptor.encrypt(256, bundle
							.getString(VAULT_PASSWORD), editTextTextData
							.getText().toString());
					boolean success = DocryptUtil.putCipherTextToFile(
							cipherText,
							vault.getDatas().get(bundle.getString(DATA_KEY))
									.getTextFileName());
					if (success) {
						Toast.makeText(getApplicationContext(),
								getString(R.string.dataSaveSuccessful),
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(getApplicationContext(),
								getString(R.string.dataSaveFailed),
								Toast.LENGTH_SHORT).show();
					}
					break;
				case DialogInterface.BUTTON_NEGATIVE:
					editTextTextData.setText(DocryptUtil.getCleanTextFromFile(
							bundle.getString(VAULT_PASSWORD), vault.getDatas()
									.get(bundle.getString(DATA_KEY))
									.getTextFileName()));
					dialog.dismiss();
					break;
				case DialogInterface.BUTTON_NEUTRAL:
					dialog.dismiss();
					break;
				}
			}
		};
		new AlertDialog.Builder(ManageDataActivity.this)
				.setCancelable(false)
				.setTitle("Confirm Save!")
				.setMessage(
						"Data : "
								+ vault.getDatas()
										.get(getIntent().getExtras().getString(
												DATA_KEY)).getName())
				.setPositiveButton("Save", confirmDialog)
				.setNegativeButton("Discard", confirmDialog)
				.setNeutralButton("Cancel", confirmDialog).show();

	}

	public void attachments(View view) {
		Intent intentAttachments = new Intent(ManageDataActivity.this,
				AttachmentsActivity.class);
		Bundle bundle = getIntent().getExtras();
		intentAttachments.putExtra(VAULT_FILE_NAME,
				bundle.getString(VAULT_FILE_NAME));
		intentAttachments.putExtra(DATA_KEY, bundle.getString(DATA_KEY));
		intentAttachments.putExtra(VAULT_PASSWORD,
				bundle.getString(VAULT_PASSWORD));
		startActivity(intentAttachments);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_manage_data, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.lockVault:
			Intent vaultsIntent = new Intent(this, VaultsActivity.class);
			vaultsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			vaultsIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(vaultsIntent);
			return true;
		case R.id.deleteData:
			final Vault vaultDataDel = DocryptUtil.getVaultFromSD(getIntent()
					.getExtras().getString(VAULT_FILE_NAME));
			DialogInterface.OnClickListener confirmDialogDeleteData = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						String dataKey = getIntent().getExtras().getString(
								DATA_KEY);
						boolean success1 = DocryptUtil.deleteDataFromSD(
								vaultDataDel, dataKey);
						vaultDataDel.getDatas().remove(dataKey);
						boolean success2 = DocryptUtil
								.putVaultToSD(vaultDataDel);
						if (success1 && success2) {
							Toast.makeText(getApplicationContext(),
									getString(R.string.dataDeleteSuccessful),
									Toast.LENGTH_SHORT).show();
							Intent datasIntent = new Intent(
									ManageDataActivity.this,
									DatasActivity.class);
							datasIntent
									.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							datasIntent
									.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
							datasIntent.putExtra(VAULT_FILE_NAME,
									vaultDataDel.getVaultFileName());
							startActivity(datasIntent);
						} else {
							Toast.makeText(getApplicationContext(),
									getString(R.string.dataDeleteFailed),
									Toast.LENGTH_SHORT).show();
						}
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			};
			new AlertDialog.Builder(ManageDataActivity.this)
					.setCancelable(false)
					.setTitle("Confirm Delete!")
					.setMessage(
							"Data : "
									+ vaultDataDel
											.getDatas()
											.get(getIntent().getExtras()
													.getString(DATA_KEY))
											.getName())
					.setPositiveButton("Delete", confirmDialogDeleteData)
					.setNegativeButton("Cancel", confirmDialogDeleteData)
					.show();
			return true;
		case R.id.deleteVault:
			final Vault vaultDel = DocryptUtil.getVaultFromSD(getIntent()
					.getExtras().getString(VAULT_FILE_NAME));
			DialogInterface.OnClickListener confirmDialogDeleteVault = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						boolean success = DocryptUtil
								.deleteVaultFromSD(vaultDel);
						if (success) {
							Toast.makeText(getApplicationContext(),
									getString(R.string.vaultDeleteSuccessful),
									Toast.LENGTH_SHORT).show();
							Intent vaultsIntent = new Intent(
									ManageDataActivity.this,
									VaultsActivity.class);
							vaultsIntent
									.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							vaultsIntent
									.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
							startActivity(vaultsIntent);
						} else {
							Toast.makeText(getApplicationContext(),
									getString(R.string.vaultDeleteFailed),
									Toast.LENGTH_SHORT).show();
						}
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			};
			new AlertDialog.Builder(ManageDataActivity.this)
					.setCancelable(false).setTitle("Confirm Delete!")
					.setMessage("Vault : " + vaultDel.getName())
					.setPositiveButton("Delete", confirmDialogDeleteVault)
					.setNegativeButton("Cancel", confirmDialogDeleteVault)
					.show();
			return true;
		case R.id.help:
			Intent helpActivity = new Intent(this, HelpActivity.class);
			startActivity(helpActivity);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
